<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API 测试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .section {
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: 5px;
        }
        .result {
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 5px;
            white-space: pre-wrap;
            font-family: monospace;
        }
        button {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        input, textarea {
            width: 100%;
            padding: 8px;
            margin: 5px 0;
            box-sizing: border-box;
        }
        .status {
            padding: 5px;
            margin: 5px 0;
            border-radius: 3px;
        }
        .success {
            background-color: #dff0d8;
            color: #3c763d;
        }
        .error {
            background-color: #f2dede;
            color: #a94442;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>API 测试页面</h1>
        
        <div class="section">
            <h2>健康检查</h2>
            <button onclick="testHealthCheck()">测试健康检查</button>
            <div id="health-result" class="result"></div>
        </div>
        
        <div class="section">
            <h2>聊天API测试</h2>
            <div>
                <label for="session-id">会话ID:</label>
                <input type="text" id="session-id" value="test-session-123">
            </div>
            <div>
                <label for="message">消息:</label>
                <textarea id="message" rows="3">你好，这是一个测试消息</textarea>
            </div>
            <div>
                <label>
                    <input type="checkbox" id="stream" checked> 使用流式响应
                </label>
            </div>
            <button onclick="testChatAPI()">发送消息</button>
            <div id="chat-status" class="status"></div>
            <div id="chat-result" class="result"></div>
        </div>
    </div>

    <script>
        const API_BASE_URL = 'http://127.0.0.1:8001';
        
        // 测试健康检查
        async function testHealthCheck() {
            const resultDiv = document.getElementById('health-result');
            resultDiv.textContent = '正在测试...';
            
            try {
                const response = await fetch(`${API_BASE_URL}/`);
                const data = await response.json();
                
                resultDiv.textContent = `状态码: ${response.status}\n${JSON.stringify(data, null, 2)}`;
                resultDiv.className = 'result success';
            } catch (error) {
                resultDiv.textContent = `错误: ${error.message}`;
                resultDiv.className = 'result error';
            }
        }
        
        // 测试聊天API
        async function testChatAPI() {
            const sessionId = document.getElementById('session-id').value;
            const message = document.getElementById('message').value;
            const useStream = document.getElementById('stream').checked;
            
            const statusDiv = document.getElementById('chat-status');
            const resultDiv = document.getElementById('chat-result');
            
            statusDiv.textContent = '正在发送消息...';
            statusDiv.className = 'status';
            resultDiv.textContent = '';
            
            const requestBody = {
                session_id: sessionId,
                message: message,
                use_rag: false,
                use_tools: false,
                stream: useStream
            };
            
            try {
                const response = await fetch(`${API_BASE_URL}/v1/chat/`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': useStream ? 'text/event-stream' : 'application/json'
                    },
                    body: JSON.stringify(requestBody)
                });
                
                if (useStream) {
                    // 处理流式响应
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    let buffer = '';
                    
                    statusDiv.textContent = '接收流式响应...';
                    statusDiv.className = 'status success';
                    
                    while (true) {
                        const { done, value } = await reader.read();
                        
                        if (done) {
                            statusDiv.textContent = '流式响应完成';
                            break;
                        }
                        
                        buffer += decoder.decode(value, { stream: true });
                        
                        // 处理SSE事件
                        while (true) {
                            const newlineIndex = buffer.indexOf('\n\n');
                            if (newlineIndex === -1) break;
                            
                            const eventData = buffer.substring(0, newlineIndex);
                            buffer = buffer.substring(newlineIndex + 2);
                            
                            if (eventData.startsWith('data: ')) {
                                const dataContent = eventData.substring(6);
                                try {
                                    const parsed = JSON.parse(dataContent);
                                    if (parsed.type === 'chunk' && parsed.content) {
                                        resultDiv.textContent += parsed.content;
                                    } else if (parsed.type === 'error') {
                                        statusDiv.textContent = `错误: ${parsed.content}`;
                                        statusDiv.className = 'status error';
                                    } else if (parsed.type === 'done') {
                                        statusDiv.textContent = '流式响应完成';
                                    }
                                } catch (e) {
                                    resultDiv.textContent += dataContent + '\n';
                                }
                            }
                        }
                    }
                } else {
                    // 处理非流式响应
                    const data = await response.json();
                    
                    statusDiv.textContent = `状态码: ${response.status}`;
                    statusDiv.className = response.ok ? 'status success' : 'status error';
                    resultDiv.textContent = JSON.stringify(data, null, 2);
                }
            } catch (error) {
                statusDiv.textContent = `错误: ${error.message}`;
                statusDiv.className = 'status error';
            }
        }
        
        // 页面加载时自动测试健康检查
        window.onload = function() {
            testHealthCheck();
        };
    </script>
</body>
</html>